package com.google.code.server4j.connector.bio;

import java.net.Socket;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.google.code.server4j.connector.HttpProcessor;
import com.google.code.server4j.connector.ProcessAdapter;
import com.google.code.server4j.handler.ServerHandler;

public class BioProcessAdapter implements ProcessAdapter {

	private ServerHandler handler;
	
	public void setHandler(ServerHandler handler) {
		this.handler = handler;
	}

	private ConcurrentLinkedQueue<BioHttpProcessor> queue = new ConcurrentLinkedQueue<BioHttpProcessor>();
	@Override
	public boolean process(Socket socket) {
		BioHttpProcessor processor = queue.poll();
		if(processor == null) {
			processor = createBioHttpProcessor();
			processor.init();
		}
		processor.process(socket);
		queue.offer(processor);
		return false;
	}
	
	private BioHttpProcessor createBioHttpProcessor() {
		BioHttpProcessor processor = new BioHttpProcessor();
		processor.setHandler(handler);
		processor.setSocketTimeOut(20 * 1000);
		return processor;
	}

}
